<?php

class Administrator extends A_Content {

	private $_admin_list = array();
	
	public function __construct($top,$parent) {
		parent::__construct($top,$parent);
		
		
		$get_admins = $this->_top->_sql->exe('SELECT `administrator_id` FROM `'.TAB_PREF.'administrator` WHERE 1 ORDER BY `administrator_id` ASC');
		for ($a=0;$a<count($get_admins);$a++) {
			array_push($this->_admin_list,$get_admins[$a]['administrator_id']);
		}
	}
	
	public function length() {
		return count($this->_admin_list);
	}
	
	/**
	 * Returns pointer to SingleAdministrator class
	 *
	 * @param int $idx - index of administrator note in found list
	 * @return SingleAdministrator
	 */
	public function item($idx) {
		return $this->getById($this->_admin_list[$idx]);
	}
	
	public function __get($param) {
		if ($param=='length') {
			return $this->length();
		}
	}
	
	/**
	 * Return pointer to SingleAdministrator class by ID
	 *
	 * @param int $id - admin id
	 * @return SingleAdministrator
	 */
	public function getById($id) {
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleAdministrator($this->_top,$this,$id);
		}
		
		return $this->_cashe_obj[$id]; 
	}
	
	/**
	 * Adds new administrator and returns pointer to it's class
	 *
	 * @return SingleAdministrator
	 */
	public function add()
	{
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator` WHERE `login`=''");
		$this->_top->_sql->exeDummy('INSERT INTO `'.TAB_PREF.'administrator` (add_date) VALUES (NOW());');
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}
	
	/**
	 * Returns pointer to SearchAdministrator class
	 *
	 * @return SearchAdministrator
	 */
	public function search() {
		return new SearchAdministrator($this->_top,$this);
	}
	
	/**
	 * Removes all priveleges from menu point
	 *
	 * @param MenuItem|Integer $menu - пункт меню
	 */
	public function clearPrev($menu) {
		if (gettype($menu)!='object') {
			$menu = $this->_top->Menu->getPointById($menu);
		}
		
		for ($a=0;$a<$this->length();$a++) {
			$this->item($a)->unlinkMenu($menu);
		}
	}
	
	/**
	 * Copies menu permissions from parent point. Using only for just created points!
	 *
	 * @param MenuItem|Integer $menu - пункт меню
	 */
	public function copyPrev($menu) {
		if (gettype($menu)!='object') {
			$menu = $this->_top->Menu->getPointById($menu);
		}
		
		for ($a=0;$a<$this->length();$a++) {
			if ($this->item($a)->checkMenu($menu->parent)) {
				$this->item($a)->linkMenu($menu);
			}
		}
	}
	
}

class SearchAdministrator extends A_Content {

	public $login;
	public $login_exact;
	public $name;
	public $group_id;
	public $rule = 'AND';
	
	private $_admin_list = array();
	
	/**
	 * Starts searching
	 *
	 * @return self
	 */
	public function Make() {
		$from_list = array('`'.TAB_PREF.'administrator` as a');
		$where_list = array();
		
		if ($this->login_exact!==NULL) {
			array_push($where_list,'a.`login`="'.$this->_top->Utils->prepareValueForSQL($this->login_exact).'"');
		} elseif ($this->login!==NULL) {
			array_push($where_list,'LOWER(a.`login`) LIKE LOWER("'.$this->_top->Utils->prepareValueForSQL($this->login).'%")');
		}
		if ($this->name!==NULL) {
			array_push($where_list,'LOWER(a.`name`) LIKE LOWER("%'.$this->_top->Utils->prepareValueForSQL($this->name).'%")');
		}
		
		if ($this->group_id!==NULL) {
			array_push($from_list,'`'.TAB_PREF.'administrator2group` as l');
			array_push($where_list,'(a.`administrator_id`=l.`administrator_id` AND l.`group_id`="'.$this->group_id.'")');
		}
		$sql = 'SELECT a.`administrator_id` FROM '.implode(',',$from_list).' WHERE '.(count($where_list)==0 ? '1' : implode(' '.$this->rule.' ',$where_list)).' ORDER BY a.`administrator_id` ASC';
		$get_admins = $this->_top->_sql->exe($sql);
		for ($a=0;$a<count($get_admins);$a++) {
			array_push($this->_admin_list,$get_admins[$a]['administrator_id']);
		}
		
		return $this;
	}
	
	public function length() {
		return count($this->_admin_list);
	}
	
	/**
	 * Returns pointer to SingleAdministrator class
	 *
	 * @param int $idx - index of administrator note in found list
	 * @return SingleAdministrator
	 */
	public function item($idx) {
		return $this->_parent->getById($this->_admin_list[$idx]);
	}
	
	public function __get($param) {
		if ($param=='length') {
			return $this->length();
		}
	}
	
	/**
	 * Return pointer to SingleAdministrator class by ID
	 *
	 * @param int $id - admin id
	 * @return SingleAdministrator
	 */
	public function getById($id) {
		$this->_parent->getById($id);
	}
	
	/**
	 * Adds new administrator and returns pointer to it's class
	 *
	 * @return SingleAdministrator
	 */
	public function add() {
		$this->_parent->add();
	}
	
	
}

class SingleAdministrator extends A_SingleContent {


	private 
		$_modules = array(),
		$_groups = array(),
		$_menu = array();
	
	protected function loader() {
		$get_data = $this->_top->_sql->exe("SELECT * FROM `".TAB_PREF."administrator` WHERE `administrator_id`={$this->_content_id}");
		
		if (count($get_data)==0)
			throw $this->_top->Utils->PushError("Administrator Id: {$this->_content_id} not found","Системная ошибка. Обратитесь к администратору");
		else {
			$this->_data = $get_data[0];
		}
		return true;
	}
	
	/**
	 * Checks password
	 *
	 * @param string $pass
	 * @return boolean
	 */
	public function checkPass($pass) {
		return $this->password==strtolower(md5($pass));
	}
	
	
	public function __set($param,$value) {
		if (!isset($this->_data[$param])) {
			throw $this->_top->Utils->PushError('Seting Undefinded Administrator object property: '.$param,'Системная ошибка. Обратитесь к разработчикам');
		} elseif ($param=='administrator_id' || $param=='add_date') {
			throw $this->_top->Utils->PushError('Trying to set Read only Administrator object property','Системная ошибка. Обратитесь к разработчикам');
		} elseif ($param=='login') {
			if ($this->login!='') {
				throw $this->_top->Utils->PushError('Administrator login is allready set','Системная ошибка. Обратитесь к разработчикам');
			} else {
				$login_search = $this->_top->Administrator->search();
				$login_search->login = $value;
				$login_search->Make();
				if ($login_search->length()>0) {
					throw $this->_top->Utils->PushError('Login is not unique','Логин не уникальный.');
				}
			}
		} elseif ($param=='password') {
			$value = strtolower(md5($value));
		} elseif ($param=='is_blocked' && ($value!='1' && $value!='0')) {
			throw $this->_top->Utils->PushError('Trying to set illegal Administrator blocked value','Системная ошибка. Обратитесь к разработчикам');
		}
		
		$this->_data[$param] = $value;
		
		$value = $this->_top->Utils->prepareValueForSQL($value);
		
		$this->_top->_sql->exeDummy("UPDATE `".TAB_PREF."administrator` SET `$param`='$value' WHERE `administrator_id`={$this->_content_id}");
		
	}
	
	protected function deleter() {
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator` WHERE `administrator_id`='{$this->_content_id}'");
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator2group` WHERE `administrator_id`='{$this->_content_id}'");
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator2menu` WHERE `administrator_id`='{$this->_content_id}'");
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator2modul` WHERE `administrator_id`='{$this->_content_id}'");
		
		unset($this->_data);
	}
	
	
	public function __get($param) {
		return $this->_data[$param];
	}
	
	/**
	 * Returns list of linked gorups
	 *
	 * @return SearchAdminGroup
	 */
	public function groupList() {
		$groupList = $this->_top->AdminGroup->search();
		$groupList->admin_id = $this->_content_id;
		return $groupList->Make();
	}
	
	
	/**
	 * Links admin to group
	 *
	 * @param SearchAdminGroup|integer $group
	 */
	public function linkGroup($group) {
		if (gettype($group)=='object') {
			$group = $group->group_id;
		}
		
		if (!$this->checkGroup($group)) {
			$this->_groups[$group] = true;
			$this->_top->_sql->exeDummy("INSERT INTO `".TAB_PREF."administrator2group` (`administrator_id`,`group_id`)
				VALUES ('{$this->_content_id}','{$group}')");
		}
	}
	
	/**
	 * Unlinks admin to group
	 *
	 * @param SearchAdminGroup|integer $group
	 */
	public function unlinkGroup($group) {
		if (gettype($group)=='object') {
			$group = $group->group_id;
		}
		
		$this->_groups[$group] = false;
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator2group`
			WHERE `administrator_id`='{$this->_content_id}' AND `group_id`='{$group}'");
	}
	
	/**
	 * Links admin to group
	 *
	 * @param SearchAdminGroup|integer $group
	 * @return boolean
	 */
	public function checkGroup($group) {
		if (gettype($group)=='object') {
			$group = $group->group_id;
		}
		
		if (!isset($this->_groups[$group])) {
			$check_group = $this->_top->_sql->exe("SELECT * FROM `".TAB_PREF."administrator2group` 
				WHERE `administrator_id`='{$this->_content_id}' AND `group_id`='{$group}'");
			$this->_groups[$group] = count($check_group)==0 ? false : true;
		}
		
		return $this->_groups[$group];
	}
	
	
	/**
	 * Adds rights to manage module
	 *
	 * @param string $key - module key name
	 */
	public function linkModule($key) {
		if (!$this->checkModule($key)) {
			$this->_modules[$key] = true;
			$this->_top->_sql->exeDummy("INSERT INTO `".TAB_PREF."administrator2module` (`administrator_id`,`module`)
				VALUES ({$this->_content_id},'{$key}')");
		}
	}
	
	/**
	 * Removes rights to manage module
	 *
	 * @param string $key - module key name
	 */
	public function unlinkModule($key) {
		$this->_modules[$key] = false;
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator2module`
			WHERE `administrator_id`={$this->_content_id} AND `module`='{$key}'");
	}
	
	
	/**
	 * Checks if administrator has rights to manage module
	 *
	 * @param string $key - module key name
	 */
	public function checkModule($key) {
		if (!isset($this->_modules[$key])) {
			$check_module = $this->_top->_sql->exe("SELECT * FROM `".TAB_PREF."administrator2module` 
				WHERE `administrator_id`={$this->_content_id} AND `module`='{$key}'");
			$this->_modules[$key] = count($check_module)==0 ? false : true;
		}
		
		return $this->_modules[$key];
	}
	

	/**
	 * Adds rights to manage menu point
	 *
	 * @param SingleMenu|String $menu
	 */
	public function linkMenu($menu) {
		if (gettype($menu)=='object') {
			$menu = $menu->menu_id;
		}
		
		if (!$this->checkMenu($menu)) {
			$this->_menu[$menu] = true;
			$this->_top->_sql->exeDummy("INSERT INTO `".TAB_PREF."administrator2menu` (`administrator_id`,`menu_id`)
				VALUES ({$this->_content_id},'{$menu}')");
		}
	}
	
	/**
	 * Removes rights to manage menu point
	 *
	 * @param SingleMenu|String $menu
	 */
	public function unlinkMenu($menu) {
		if (gettype($menu)=='object') {
			$menu = $menu->menu_id;
		}
		
		$this->_menu[$menu] = false;
		$this->_top->_sql->exeDummy("DELETE FROM `".TAB_PREF."administrator2menu`
			WHERE `administrator_id`={$this->_content_id} AND `menu_id`='{$menu}'");
	}
	
	/**
	 * Checkin if admin has rights to manage menu
	 *
	 * @param SingleMenu|String $menu
	 * @return boolean
	 */
	public function checkMenu($menu) {
		if (gettype($menu)=='object') {
			$menu = $menu->menu_id;
		}
		
		if (!isset($this->_menu[$menu])) {
			$check_menu = $this->_top->_sql->exe("SELECT * FROM `".TAB_PREF."administrator2menu` 
				WHERE `administrator_id`={$this->_content_id} AND `menu_id`='{$menu}'");
			$this->_menu[$menu] = count($check_menu)==0 ? false : true;
		}
		
		return $this->_menu[$menu];
	}
	
	
	
	
}
?>